package com.solarfridge.testclient;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

public class MonitorConnection extends HttpServerConnection {
	
	public static int RESULT_OK = 0;
	public static int RESULT_INVALID_ID = RESULT_OK + 1;
	public static int RESULT_BAD_PASSWORD = RESULT_INVALID_ID + 1;
	public static int RESULT_LOGGING_DISABLED = RESULT_BAD_PASSWORD + 1;
	public static int RESULT_MALFORMED = RESULT_LOGGING_DISABLED + 1;

	public static String TYPE_CHECK = "CONNECTION";
	public static String TYPE_SALT = "SALT";
	public static String TYPE_POST = "POST_DATA";

	public static String KEY_FRIDGE_ID = "FridgeId";
	public static String KEY_TYPE = "Type";
	public static String KEY_SALT = "Salt";
	public static String KEY_ATEMP = "Atemp";
	public static String KEY_FTEMP  = "Ftemp";
	public static String KEY_CTEMP = "Ctemp";
	public static String KEY_CSUN = "Csun";
	public static String KEY_TIME = "Time";
	public static String KEY_KEY = "Key";
	public static String KEY_RESULT = "Result";
	
	private final String mFridgeId;

	public MonitorConnection(String url, String fridgeId) {
		super(url);
		mFridgeId = fridgeId;
	}
	
	/**
	 * Test connection to the server.
	 * @return See result codes.
	 */
	public int testConnection(){
		HttpParamList params = new HttpParamList();
		
		params.add(new BasicNameValuePair(KEY_FRIDGE_ID, mFridgeId));
		params.add(new BasicNameValuePair(KEY_TYPE, TYPE_CHECK));
		
		int returnCode = RESULT_INVALID_ID;
		
		try {
			HttpResponse resp = this.doPost(params);
			Header id = resp.getFirstHeader(KEY_FRIDGE_ID);
			
			Header type = resp.getFirstHeader(KEY_TYPE);
			
			if((id != null && id.getValue().equals(mFridgeId)) && (type != null && type.getValue().equals(TYPE_CHECK))){
				returnCode = RESULT_OK;
			} else {
				returnCode = RESULT_MALFORMED;
			}
		} catch (ClientProtocolException e) {
			returnCode = RESULT_MALFORMED;
			e.printStackTrace();
		} catch (IOException e) {
			returnCode = RESULT_MALFORMED;
			e.printStackTrace();
		}
		        
        return returnCode;
	}
}
